<script lang="ts" setup>
import { ref } from 'vue';
import { isBefore, subDays } from 'date-fns';
import type { FormInstance } from '@arco-design/web-vue/es/form';
import { $fetch } from '@/settings/utils/fetch';
import useNotification from '@/settings/hooks/notification';
import { useRouter } from 'vue-router';
import { operateTypeMap } from './use';
import { useI18n } from 'vue-i18n';

const props = defineProps({
  pageType: {
    type: String,
    default: 'banner',
  },

  id: {
    type: String,
    default: '',
  },
});

const type = ref('1')
const loading = ref(false);
const formData = ref({
  operateName: '',
  jumpUrl: '',
  picUrl: '',
  sort: 0,
  times: [] as string[],
});
const formRef = ref<FormInstance>();
const router = useRouter();
const { success } = useNotification();
const { t } = useI18n();
const operateType = operateTypeMap[props.pageType];

const getTypeBasedOnTime = (startTime: string | null, endTime: string | null): string => {
  if (startTime && endTime) {
    return '1'; // 如果存在开始时间和结束时间，则 type 为 1
  } else {
    return '2'; // 如果不存在开始时间或结束时间，则 type 为 2
  }
};

const save = async () => {
  const params: Record<string, any> = {
    operateType,
    operateId: props.id,
    ...formData.value,
  }

  if (type.value === '1') {
    params.showStartTime = formData.value.times?.[0];
    params.showEndTime = formData.value.times?.[1];
  }

  delete params.times;

  const { isSuccess } = await $fetch(props.id ? '/admin/operator/updateOperator' : '/admin/operator/addOperator', {
    method: 'post',
    data: params,
    loadingStatus: loading,
  });

  if (isSuccess) {
    success(t('settings.notification.success'));
    router.push(`/operator/${props.pageType}/index`);
  }
};

const submit = async () => {
  const res = await formRef.value?.validate();

  if (res) {
    return;
  }

  save();
};

const getDetail = async () => {
  const { isSuccess, data } = await $fetch('/admin/operator/getOperateById', {
    method: 'get',
    data: {
      operateType,
      operateId: props.id,
    },
    loadingStatus: loading,
  });

  if (isSuccess) {
    type.value = getTypeBasedOnTime(data.showStartTime, data.showEndTime);
    formData.value = {
      operateName: data.operateName,
      picUrl: data.picUrl,
      jumpUrl: data.jumpUrl,
      sort: data.sort,
      times: [data.showStartTime, data.showEndTime],
    };
  }
}

const isCurrentBeforeNow = (current: Date) => {
  const now = new Date();
  return isBefore(current, subDays(now, 1));
};

const init = () => {
  if (props.id) {
    getDetail();
  }
}

init();
</script>

<template>
  <OpenPageSection>
    <OpenGeneralCard>
      <AForm ref="formRef" auto-label-width scroll-to-first-error :model="formData" @submit="submit">
        <AFormItem :label="$t('settings.view.operation.edit.colum1')" field="operateName" :rules="[{ required: true, message: $t('settings.notification.required') }, { maxLength: 150 }]">
          <AInput v-model="formData.operateName" :max-length="150" allow-clear show-word-limit />
        </AFormItem>

        <AFormItem
          :label="$t('settings.view.operation.edit.colum2')" field="picUrl" :rules="[{ required: true, message: $t('settings.notification.required') }]"
          :help="props.pageType === 'banner' ? $t('settings.view.operation.edit.tips1') : $t('settings.view.operation.edit.tips2')"
        >
          <OpenUpload v-model="formData.picUrl" />
        </AFormItem>

        <AFormItem :label="$t('settings.view.operation.edit.colum3')" field="jumpUrl" :rules="[{ maxLength: 150 }]">
          <AInput v-model.trim="formData.jumpUrl" :max-length="150" allow-clear show-word-limit />
        </AFormItem>

        <AFormItem :label="$t('settings.view.operation.edit.colum4')" field="sort" :rules="[{ required: true, message: $t('settings.notification.required') }]" class="w-240">
          <AInputNumber v-model="formData.sort" :default-value="0" allow-clear show-word-limit mode="button" />
        </AFormItem>

        <AFormItem :label="$t('settings.view.operation.edit.colum5')" :rules="[{ required: true, message: $t('settings.notification.required') }]" v-if="!props.id">
          <ARadioGroup v-model="type">
            <ARadio value="1">{{ $t('settings.view.operation.edit.status.1') }}</ARadio>
            <ARadio value="2">{{ $t('settings.view.operation.edit.status.2') }}</ARadio>
          </ARadioGroup>
        </AFormItem>

        <AFormItem :label="$t('settings.view.operation.edit.colum6')" field="times" :rules="[{ required: true, message: $t('settings.notification.required') }]" v-if="type === '1'">
          <ARangePicker :disabled-date="(current:any) => isCurrentBeforeNow(current ?? new Date())" show-time v-model="formData.times" />
        </AFormItem>
        <ADivider />

        <AFormItem>
          <ASpace>
            <AButton html-type="submit" type="primary" :loading="loading">{{ $t('settings.action.submit') }}</AButton>
          </ASpace>
        </AFormItem>
      </AForm>
    </OpenGeneralCard>
  </OpenPageSection>
</template>

<style lang="scss" scoped>
</style>
